// 为vuex添加routes模块,存储及修改动态路由数据
export function registerRoutesModule(store) {
  if (!store || !store.hasModule) return;
  if (!store.hasModule("qiankunRoutes")) {
    const routesModule = {
      namespaced: true,
      state: {
        qiankunRoutes: [],
      },
      actions: {
        SetQiankunRoutes({ state }, data) {
          state.qiankunRoutes = data;
        },
      },
    };
    store.registerModule("qiankunRoutes", routesModule);
  }
}

// 路由拦截那里动态加载路由
export function addSubRoutes(to, next, from, router, store, loadView) {
  if (!router.options.isAddQiankunRoutes && store.hasModule("qiankunRoutes")) {
    const addRoutes = store.state.qiankunRoutes.qiankunRoutes;
    if (addRoutes && addRoutes.length > 0) {
      addRoutes.map((item) => {
        const obj = {};
        if (item.name) {
          obj.name = item.name;
        }
        if (item.component) {
          obj.component = loadView(item.component);
        }
        if (item.path) {
          obj.path = item.path.startsWith("/") ? item.path : "/" + item.path;
        }
        router.addRoute(obj);
      });
      router.options.isAddQiankunRoutes = true;
      next({ ...to, replace: true });
    }
  }
}
